using System.Data;
using FireStarter.Base;
using Firestarter.DB.Schema.BO;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.BO.ClassDefinition;
using Habanero.BO.Loaders;
using Habanero.DB;

namespace Firestarter.DB.Schema.Test.Logic
{
    public class TestUtilsDBSchema
    {
        public static void LoadClassDefs()
        {
            ClassDef.ClassDefs.Clear();
            string xmlClassDefs = BOBroker.GetClassDefsXml();
            ClassDef.ClassDefs.Add(new XmlClassDefsLoader(xmlClassDefs, new DtdLoader()).LoadClassDefs());
        }

        public static DatabaseConnectionInfo CreateValidDatabaseConnectionInfo()
        {
            DatabaseConnectionInfo databaseConnectionInfo = new DatabaseConnectionInfo
            {
                Vendor = "MySql",
                Server = "localhost",
                Database = "information_schema",
                UserName = "root",
                Password = "root"
            };
            return databaseConnectionInfo;
        }

        public static void CreateTestDatabase(string databaseName)
        {
            IDbConnection connection = CreateTestDBConnection("information_schema");
            if (connection.State == ConnectionState.Closed) connection.Open();
            ExecuteSql(connection, string.Format("DROP DATABASE IF EXISTS {0};", databaseName));
            ExecuteSql(connection, string.Format(@"
                    CREATE DATABASE IF NOT EXISTS {0};
                    USE {0};
                    ", databaseName));
        }

/*

        public static void ClearDatabase(IDbConnection connection, string databaseName)
        {
            string sqlStatement = string.Format
                (@"
                DROP DATABASE {0};
                CREATE DATABASE {0};
                USE {0};
                ",
                 databaseName);
            ExecuteSql(connection, sqlStatement);
        }
*/

        public static void ExecuteSql(IDbConnection connection, string sql)
        {
            if (connection.State == ConnectionState.Closed) connection.Open();
            IDbCommand command = connection.CreateCommand();
            command.CommandText = sql;
            command.ExecuteNonQuery();
        }

        public static IDbConnection CreateTestDBConnection(string databaseName) {
            DatabaseConfig databaseConfig = new DatabaseConfig("Mysql", "localhost", databaseName, "root", "root", null);
            return databaseConfig.GetDatabaseConnection().GetConnection();
        }
    }
}
